
<template src='./tpl.html'></template>
<script>
import { CONSENT_GET_CONSENT_PATIENT_INFO, CONSENT_GET_CONSENT_INFO, CONSENT_GET_TEMPLATE_INFO, CONSENT_SIGN } from "_SERVICES/api";
import { simDeepCopy, getStorage, setStorage,isInteger } from "UTILS/util";
import Sign from 'MODULES/CST/components/Sign'
import draggableItem from 'MODULES/CST/components/DraggableItem'
import sign from "./sign"

export default {
  name: "consentTemplate",
  mixins: [sign],

  components: {
    'v-sign': Sign,
    draggableItem
  },
  data() {
    return {
      queryInfo: {
        TYPE: "4" //1 新增 2编辑 //3查看已签署信息 //4 查看模板
      },
      brInfo: {},
      TPL_FORMAT: [],
      templateInfo: {},
      signInfo: {},
      listLoading: false,
      saveLoading: false,
      finishLoading: false
    };
  },
  created() {
    //如果是直接传JCH 就表示这是新增一个知情同意书 带出病人信息
    //如果是主键传CONSTENT_ID 表示这是编辑一个知情同意书

    if (this.$route.query) {
      this.queryInfo = this.$route.query;
    }

    /* eslint-disable */

    this.WebSign = new jSign();

    //如果是查看，或者后端生成pdf的时候，不连接签字版，免得报错。
    console.log(this.queryInfo.TYPE)
    if (this.queryInfo.TYPE != 3 && this.queryInfo.NO_SHOW != 1) {
      // this.connectSign(val => { })
    }


    if (this.queryInfo.TYPE == 1) {
      this.get_template_info().then((res) => {
        this.get_br_info();
      });
      // {
      //   TYPE:1, 1 新增文书
      //   TID:1,//模板ID
      //   GET_PATIENT_BY_PRIMARY:1,//获取病人信息的主索引
      //   GET_PATIENT_TYPE:"NJZX" //获取病人信息的科室区分
      // }

    } else if (this.queryInfo.TYPE == 2) {
      // {
      //   TYPE:2, 2编辑文书
      //   CONSENT_ID:1,//文书ID
      // }
      this.get_consent_info();
    } else if (this.queryInfo.TYPE == 3) {
      // {
      //   TYPE:3, 3查看已签署信息
      //   CONSENT_ID:1,//文书ID
      // }
      this.get_consent_info();
    } else {
      this.get_template_info();
      // {
      //   TYPE:4, 4 查看模板
      //   TID:1,//模板ID
      // }
      //4 查看模板

    }
  },
  mounted() {
      // 将滚动条滚动到顶部位置
    const container = this.$refs.scrollContainer;
    container.scrollTop = 0;


    // const subOutputRankPrint = document.getElementById("nj_tem_1");
    // this.$print(subOutputRankPrint, {
    //   title: "",
    // });
    // console.save(document.documentElement.innerHTML,'1.html')
    // console.save(document.documentElement.outerHTML,"1.html")
  },
  methods: {
    checkParams() {
      let errorStr = "";
      this.TPL_FORMAT.forEach((item) => {
        if (item.field_value_type == 'Array' && item.field_value_required == true && item.field_value.length == 0) {
          errorStr += `<div>【` + item.label + '】不能为空</div>'
        }

        if (item.field_value_type == 'String' && item.field_value_required == true && item.field_value == "") {
          errorStr += `<div>【` + item.label + '】不能为空</div>'

        }

        if(item.type == 'MZMZ_PGB'   ) {
          let info = JSON.parse(item.field_value);
          if(!info.NXJC) {
            errorStr += `<div>【拟行检查】不能为空</div>`;
          }
        }

      })
      return errorStr;

    },

    save(finish) {
      let errorStr = this.checkParams()
      if (errorStr && finish) { //finish是最好保存的地方
        this.$alert(errorStr, '必填字段提醒', {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true,
          callback: action => {

          }
        });
        return false;
      }

      this.saveLoading = true;
      return CONSENT_SIGN({
        TPL_FORMAT: JSON.stringify(this.TPL_FORMAT),
        TID: this.templateInfo.TID,
        ZYH: this.brInfo.ZYH || "",
        BRBH: this.brInfo.BRBH || "",
        BRXM: this.brInfo.BRXM || "",
        TJBH: this.brInfo.TJBH || "",
        BLID: this.brInfo.BLID || "",
        ZYID: this.brInfo.ZYID || "",
        ZLHDID: this.brInfo.ZLHDID || "",
        GET_PATIENT_BY_PRIMARY: this.queryInfo.GET_PATIENT_BY_PRIMARY,
        GET_PATIENT_TYPE: this.queryInfo.GET_PATIENT_TYPE,
        SID: this.queryInfo.CONSENT_ID || '',
        isPublish: finish
      }).then((res) => {
        this.saveLoading = false;

        this.queryInfo = { CONSENT_ID: res.data.SID, TYPE: 2 }
        this.$router.replace({ query: { CONSENT_ID: res.data.SID, TYPE: 2 } });
        if (finish) {
          console.log("不做提示")
        } else {
          this.$message.success("保存成功");

        }
        return res;
      }).catch((e) => {
        this.saveLoading = false;
        return { code: -1 }
      })

    },
    get_br_info() {
      this.listLoading = true;
      CONSENT_GET_CONSENT_PATIENT_INFO({
        GET_PATIENT_BY_PRIMARY: this.queryInfo.GET_PATIENT_BY_PRIMARY,
        GET_PATIENT_TYPE: this.queryInfo.GET_PATIENT_TYPE,
      })
        .then((res) => {
          this.listLoading = false;

          if (res.data) {
            this.brInfo = res.data[0];
          } else {
            this.brInfo = {};
          }
          if(this.brInfo.BRXM){
            document.title= this.brInfo.BRXM
          }
          //如果是门诊病人，且送检科室是空的要设置默认值
          if (!this.brInfo.BLID && !this.brInfo.SJKS) {
            this.brInfo.SJKS = "/"
          }
          //住院号或者门诊号(构造字段)
          this.brInfo.ZYHORBRBH = this.brInfo.ZYH || this.brInfo.BRBH;

          // console.log(this.TPL_FORMAT)

          this.TPL_FORMAT.forEach((item) => {

            if (item.type == 'MZMZ_PGB') { //麻醉评估组件要特殊处理，是个json字符串

              let MZMZ_PGB_OBJ = JSON.parse(item.field_value);
              MZMZ_PGB_OBJ = {
                ...MZMZ_PGB_OBJ,
                ...this.brInfo
              }
              item.field_value = JSON.stringify(MZMZ_PGB_OBJ)

            } else {

              //*********************************************************** */
              if (this.brInfo[item.field_name]) {
                item.field_value = this.brInfo[item.field_name];
              } else {

                if (this.brInfo[item.field_name] === undefined) {
                  //LCZD_1 BRXM_!这种 要去this.brInfo匹配LCZD的数据 最后一个是数字的才去匹配。
                  // let _arr =   item.field_name.split("_");
                  let _arr = this.splitByLastUnderscore(item.field_name);//
                  if (_arr && _arr.length >= 2) {
                    if(this.brInfo[_arr[0]]!==undefined && this.brInfo[_arr[0]]!=null && this.brInfo[_arr[0]]!=""){
                      item.field_value = this.brInfo[_arr[0]]
                    }
                  } else {

                    //如果后端没有返回，但是前端又设置了。
                    if (!this.brInfo.BLID && ['ZYH', 'CWH', 'BQMC'].includes(item.field_name)) {
                      item.field_value = "/";
                    }

                  }
                } else { //不是undefined 就是说值为空的情况    //如果是门诊病人 ZYH CWH  BQMC 要设置为/
                  if (!this.brInfo.BLID && ['ZYH', 'CWH', 'BQMC'].includes(item.field_name)) {
                    item.field_value = "/";
                  }
                }

              }
              //*********************************************************** */

            }


          })
          console.log("获取病人数据", this.brInfo)

        })
        .catch((res) => {
          console.log("获取病人数据报错", res)
          this.listLoading = false;
        });
    },
    splitByLastUnderscore(str) {
      // 找到字符串中最后一个下划线的索引位置
      var lastIndex = str.lastIndexOf('_');
      // 如果找到了下划线 并且最后一个是数字
      if (lastIndex !== -1  && isInteger(str.substring(lastIndex + 1))) {
        // 使用 substring 方法截取字符串成两段，并返回结果
        return [str.substring(0, lastIndex), str.substring(lastIndex + 1)];
      } else {
        // 如果没有找到下划线，则返回原始字符串
        return [str];
      }
    },
    get_template_info() {
      this.listLoading = true
      return CONSENT_GET_TEMPLATE_INFO({
        TID: this.queryInfo.TID
      }).then((res) => {
        this.listLoading = false;

        console.log("获取模板详情", res)
        if (res.data.length) {

          this.templateInfo = res.data[0];
          this.TPL_FORMAT = JSON.parse(this.templateInfo.TPL_FORMAT)
        } else {
          this.$message.error("未获取到对应的模板")
        }

      }).catch((e => {
        this.listLoading = false;

      }))
    },
    get_consent_info() {
      this.listLoading = true;
      CONSENT_GET_CONSENT_INFO({
        SID: this.queryInfo.CONSENT_ID
      }).then((res) => {
        // console.log("具体的一份同意书",res.data)

        this.listLoading = false;

        this.templateInfo = res.data.templateInfo; //模板信息
        let list = JSON.parse(res.data.templateInfo.TPL_FORMAT);
        let signContentInfo = res.data.signContentInfo; //签署信息

        this.signInfo = JSON.parse(JSON.stringify(res.data.signInfo));

        this.brInfo = res.data.signInfo;//病人信息

        if(this.brInfo.BRXM){
          document.title= this.brInfo.BRXM
        }

        // console.log("签署保存的字段",signContentInfo)

        list.forEach((item, index) => {
          signContentInfo.forEach((inner, inner_index) => {

            if (item.field_name == inner.FIELD_NAME) {
              let value = inner.CONTENT || inner.CONTENT_CLOB;
              if (value !== null) {
                item.field_value = value;
              }
            }


            // if ((item.type == 'sign2' || item.type == 'sign3')) {
            //   if (item.field_name == inner.FIELD_NAME && inner.CONTENT_CLOB !== null) {
            //     item.field_value = inner.CONTENT_CLOB
            //   }

            // } else {
            //   if (item.field_name == inner.FIELD_NAME && inner.CONTENT !== null) {
            //     item.field_value = inner.CONTENT
            //   }
            // }

          })
        });
        this.TPL_FORMAT = list;
      }).catch((e) => {
        this.listLoading = false;
      })
    },

    back() {
      this.$router.go(-1)
    }
  },
};
</script>

<style lang="less">
.consent-template {
  .save-box {
    position: fixed;
    bottom: 0px;
    left: 0px;
    width: 100%;
    text-align: center;
    background: #fff;
    padding: 10px;
    border-top: 1px solid #efefef;
    z-index: 4;
  }
}
</style>
